<template>
  <div class="dashboard-container">
    <!-- 左侧边栏 -->
    <LaySide />

    <!-- 主内容区 -->
    <el-container class="dashboard-main">
      <Header />
      <Main />
    </el-container>

    <!-- 添加好友对话框 -->
    <el-dialog
      v-model="dashboardStore.showAddFriend"
      title="添加好友"
      width="400px"
      class="add-friend-dialog"
      :close-on-click-modal="false"
    >
      <el-input
        v-model="searchFriend"
        placeholder="搜索用户..."
        :prefix-icon="Search"
        class="search-input"
        @input="getUserData"
      />

      <div class="search-results">
        <div v-for="user in searchResults" :key="user._id" class="result-item">
          <el-avatar :size="40" :src="user.avatar">
            {{ user.username }}
          </el-avatar>
          <div class="user-info">
            <div class="user-name">{{ user.username }}</div>
            <div class="user-email">{{ user.email }}</div>
          </div>
          <el-button size="small" v-if="user._id == myUserId"> 本人 </el-button>
          <el-button
            v-else
            size="small"
            :class="{ 'is-added': isAlreadyFriend(user._id) }"
            @click="addFriend(user)"
          >
            {{ isAlreadyFriend(user._id) ? "已添加" : "添加" }}
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 聊天窗口 -->
    <div class="chat-windows">
      <div
        v-for="chat in dashboardStore.activeChats"
        :key="chat.id"
        class="chat-window"
      >
        <div class="chat-header">
          <div class="user-info">
            <el-avatar :size="32" :src="chat.friend.avatar">
              {{ chat.friend.name.charAt(0) }}
            </el-avatar>
            <span class="user-name">{{ chat.friend.name }}</span>
          </div>
          <div class="header-actions">
            <el-button circle @click="closeChat(chat)">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>

        <div class="chat-messages" ref="messagesList">
          <div
            v-for="message in chat.messages"
            :key="message.id"
            :class="['message', message.isSelf ? 'self' : 'other']"
          >
            {{ message.content }}
            <div class="message-time">
              {{ formatMessageTime(message.timestamp) }}
            </div>
          </div>
        </div>

        <div class="chat-input">
          <el-input
            v-model="chat.draft"
            placeholder="输入消息..."
            @keyup.enter="sendMessage(chat)"
          />
          <el-button circle class="send-button" @click="sendMessage(chat)">
            <el-icon><ChatDotRound /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 消息中心抽屉 -->
    <el-drawer
      v-model="dashboardStore.showMessageCenter"
      title="消息中心"
      direction="rtl"
      size="380px"
    >
      <template #header>
        <div class="message-header">
          <span>消息中心</span>
          <!-- <el-button-group>
            <el-button size="small" @click="readAll"> 全部已读 </el-button>
            <el-button size="small" @click="clearAll"> 清空消息 </el-button>
          </el-button-group> -->
        </div>
      </template>

      <div class="message-list">
        <div
          v-for="msg in messages"
          :key="msg._id"
          :class="['message-item', { unread: msg.status==0 }]"
          @click="handleMessageAction(msg)"
        >
          <el-avatar :size="40" :src="msg.sendUserMessage.avatar">
            {{ userStore.user.username }}
          </el-avatar>
          <div class="message-content">
            <div class="message-title">
              <span class="sender">{{ msg.sendUserMessage.username || "系统消息" }}</span>
              <span class="time">{{ formatMessageTime(msg.createdAt) }}</span>
            </div>
            <div class="message-text">{{ msg.content }}</div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 修改头像对话框 -->
    <el-dialog
      v-model="dashboardStore.showAvatarDialog"
      title="修改头像"
      width="400px"
    >
      <el-upload
        class="avatar-uploader"
        action="/api/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img
          v-if="currentUser.avatar"
          :src="currentUser.avatar"
          class="avatar"
        />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-dialog>
    <!-- 消息详情弹框 -->
    <DialogMessage ref="dialogMessageEl" :data="messageObj"></DialogMessage>
    <!-- 个人信息抽屉 -->
    <user-profile
      v-model="dashboardStore.showProfile"
      :user-info="userProfile"
      @save="saveProfile"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted } from "vue";
import LaySide from "../components/LaySide.vue";
import Header from "../components/Header.vue";
import Main from "../components/Main.vue";
import DialogMessage from "../components/DialogMessage.vue";
import { useRouter } from "vue-router";
import store from "../stores/module/dashboard";
import WebSocketService from "../utils/websocket.ts";
import { getUserList } from "../api/user/index.ts";
import { createMessage,list,readMessage } from "../api/message/index.ts";
import {
  Search,
  Plus,
  ChatDotRound,
  Close
} from "@element-plus/icons-vue";
import {
  currentUser as mockCurrentUser,
} from "../mock/data";
import { ElMessage } from "element-plus";
import UserProfile from "@/components/UserProfile.vue";
import useUserStore from '../stores/module/user';
const userStore = useUserStore()
// 类型定义
interface UserInfo {
  id: string;
  name: string;
  avatar: string;
  email?: string;
  status?: string;
}
interface ChatMessage {
  id: string;
  content: string;
  isSelf: boolean;
  timestamp: Date;
}

interface Chat {
  id: string;
  friend: UserInfo;
  messages: ChatMessage[];
  draft: string;
}
const router = useRouter();
const dashboardStore = store();
const messageObj = ref({})
const searchFriend = ref("");
const myUserId = ref(JSON.parse(localStorage.getItem("user") as string)._id);
const activeChats = ref<Chat[]>([]);
// 使用模拟数据
const currentUser = ref(mockCurrentUser);
const searchResults: any = ref([]);
const unreadCount = ref(3);
const messages:any = ref([]);
const dialogMessageEl = ref()
const userProfile = ref({
  ...currentUser.value,
  phone: "13800138000",
  bio: "热爱工作，享受生活",
  createdAt: "2024-01-01",
  sheetCount: 12,
  collaborationCount: 8,
  friendCount: 0,
});
// 添加好友
const addFriend = async (user: { _id: any; }) => {
  let result:any = await createMessage({
    sendUser: myUserId.value,
    receptionUser: user._id,
    status: '0',
    content: `${JSON.parse(localStorage.getItem('user') as string).username}向您发送一条好友请求`,
    type: "0",
  })
  if (result.code === 200) {
    ElMessage.success("好友申请已发送");
    WebSocketService.send({type: "0",sendUser:JSON.parse(localStorage.getItem('user') as string),receptionUser:user._id})
  }
};

// 关闭聊天
const closeChat = (chat: Chat) => {
  const index = activeChats.value.findIndex((c) => c.id === chat.id);
  if (index > -1) {
    activeChats.value.splice(index, 1);
  }
};

// 发送消息
const sendMessage = (chat: Chat) => {
  if (chat.draft.trim()) {
    // 发送消息
    const message = {
      id: Math.random().toString(36).substr(2, 9),
      content: chat.draft,
      isSelf: true,
      timestamp: new Date(),
    };
    chat.messages.push(message);
    chat.draft = ""; // 清空输入框

    // 模拟自动回复
    setTimeout(() => {
      const autoReply = {
        id: Math.random().toString(36).substr(2, 9),
        content: `这是来自 ${chat.friend.name} 的自动回复消息`,
        isSelf: false,
        timestamp: new Date(),
      };
      chat.messages.push(autoReply);
    }, 1000);

    // 显示发送成功提示
    ElMessage.success("消息发送成功");
  }
};

// 添加消息时间格式化函数
const formatMessageTime = (timestamp: Date) => {
  const now = new Date();
  const messageDate = new Date(timestamp);

  if (now.toDateString() === messageDate.toDateString()) {
    return messageDate.toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });
  }
  return messageDate.toLocaleDateString("zh-CN", {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 添加自动滚动到底部功能
watch(
  () => activeChats.value.map((chat) => chat.messages.length),
  () => {
    nextTick(() => {
      const messagesList = document.querySelectorAll(".chat-messages");
      messagesList.forEach((list) => {
        list.scrollTop = list.scrollHeight;
      });
    });
  }
);
watch(()=>dashboardStore.unreadCount,()=>{
  getMessageList()
})
// 添加检查是否已经是好友的方法
const isAlreadyFriend = (userId: string) => {
  return JSON.parse(localStorage.getItem('user') as string).friendList.some((friend: { _id: string; }) => friend._id === userId);
};
// 消息处理
const readAll = () => {
  messages.value.forEach((msg: { read: boolean; }) => (msg.read = true));
  unreadCount.value = 0;
};

const clearAll = () => {
  messages.value = [];
  unreadCount.value = 0;
};

const handleMessageAction = async(message: any) => {
  if(message.status == 0){
    await readMessage({id:message._id,status:'1'});
  }
  if(message.type == 3){
    router.push(`/sheet/${message.sheetId}/${JSON.parse(localStorage.getItem('user') as string)._id}`);
  }else{
    dialogMessageEl.value.flag = true
    messageObj.value = message
  }
  getMessageList()
};

// 保存个人信息
const saveProfile = (data: any) => {
  Object.assign(userProfile.value, data);
  Object.assign(currentUser.value, {
    name: data.name,
    email: data.email,
  });
};
const getUserData = async () => {
  if (!searchFriend.value) return;
  let result = await getUserList(searchFriend.value);
  searchResults.value = result.data;
};
const getMessageList = async () => {
  let result:any = await list(JSON.parse(localStorage.getItem("user")  as string)._id);
  messages.value = result.data;
  dashboardStore.unreadCount = messages.value.filter((item: { status: number; })=>item.status == 0).length
}
watch(()=>dashboardStore.showMessageCenter,(newValue, _oldValue)=>{
  if(newValue) {
    getMessageList()
  }
})
onMounted(() => {
  getMessageList()
  if (!WebSocketService.socket) {
    WebSocketService.connect();
  }
});
</script>

<style lang="scss">
// 只保留基础布局样式
.dashboard-container {
  display: flex;
  height: 100vh;
  background: var(--background);
}

/* 添加或修改样式 */
.create-btn {
  background: var(--primary-gradient);
  border: none;
  padding: 8px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;

  .el-icon {
    font-size: 16px;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 200, 83, 0.2);
  }

  &:active {
    transform: translateY(0);
  }
}
</style>
